<?php
namespace common\components;
use Yii;
use yii\helpers\Html;
use yii\web\Cookie;

class GridView extends \yii\grid\GridView
{
    public $minColumns = 8;
    public $showColumns = true;
    public $select_columns = 'select_columns';
    private $_cookieName = null;
    private $_cookieFields = [];
    private $_html;//复选框显示列表
    public function init() {
        $attributeLabels = [];
        if($this->dataProvider instanceof ActiveDataProvider){
            $attributeLabels    = $this->dataProvider->model->attributeLabels();
            $this->_cookieName  = md5(get_class($this->dataProvider->model));
        }else{
            $models = $this->dataProvider->getModels();
            if($models){
                $attributeLabels = $models[0]->attributeLabels();
                $this->_cookieName  = md5(get_class($models[0]));
            }else{
                $this->_cookieName = md5(get_class($this->dataProvider));
            }
        }
        $showColumns = [];
        if(!empty($_COOKIE[$this->_cookieName])){
            $showColumns = explode('&', $_COOKIE[$this->_cookieName]);
        }
        foreach($this->columns as $index => $column){
            if($attributeLabels){
                if(is_string($column)){
                    $name = $column;
                    if(strpos($column, ':') !== false){
                        $temp = explode(':', $column);
                        $name = array_shift($temp);
                        if($temp[0] == 'datetime'){
                            $this->columns[$index] = ['attribute' => $name, 'value' => function ($model, $key, $index, $column){
                                $attribute = $column->attribute;
                                if($model->$attribute){
                                    return date('Y-m-d H:i:s', $model->$attribute);
                                }else{
                                    return '';
                                }
                            }];
                        }
                    }
                    if(!$showColumns || in_array($name, $showColumns)){
                        $this->_cookieFields[] = $name;
                        $this->_html .= Html::checkbox($name, true, ['label' =>$attributeLabels[$name], 'column_index' => $index]);
                    }else{
                        $this->_html .= Html::checkbox($name, false, ['label' =>$attributeLabels[$name], 'column_index' => $index]);
                    }
                }else if(is_array($column)){
                    if(isset($column['attribute'])){
                        if(!$showColumns || in_array($column['attribute'], $showColumns)){
                            $this->_cookieFields[] = $column['attribute'];
                            $this->_html .= Html::checkbox($column['attribute'], true, ['label' =>$attributeLabels[$column['attribute']], 'column_index' => $index]);
                        }else{
                            $this->_html .= Html::checkbox($column['attribute'], false, ['label' =>$attributeLabels[$column['attribute']], 'column_index' => $index]);
                        }
                    }else if(isset($column['label'])){
                        $name = md5($column['label']);
                        if(!$showColumns || in_array($name, $showColumns)){
                            $this->_cookieFields[] = $name;
                            $this->_html .= Html::checkbox($name, true, ['label' =>$column['label'], 'column_index' => $index]);
                        }else{
                            $this->_html .= Html::checkbox($name, false, ['label' =>$column['label'], 'column_index' => $index]);
                        }
                    }
                }
            }
            if(is_string($column) && in_array($column, ['_intm', '_uptm', 'lasttm'])){
                $this->columns[$index] = ['attribute' => $column, 'value' => function ($model, $key, $index, $column){
                    $attribute = $column->attribute;
                    if($model[$attribute]){
                        if(is_numeric($model[$attribute]) && strlen($model[$attribute]) == 10){
                            return date('Y-m-d H:i:s', $model[$attribute]);
                        }else{
                            return $model[$attribute];
                        }
                    }else{
                        return '';
                    }
                }
            ];
            }else if(isset($column['format']) && $column['format'] == 'datetime'){
                $this->columns[$index]['value'] = function ($model, $key, $index, $column){
                    $attribute = $column->attribute;
                    if($model[$attribute]){
                        return date('Y-m-d H:i:s', $model[$attribute]);
                    }else{
                        return '';
                    }
                };
            }

            if(isset($column['class']) && $column['class'] == 'yii\grid\ActionColumn'){
                $this->columns[$index]['class'] = 'common\components\ActionColumn';
            }
            if(isset($column['class']) && in_array($column['class'], ['common\components\ActionColumn', 'yii\grid\ActionColumn'])){
                $this->columns[$index]['header'] = '编辑';
            }
        }
        parent::init();
    }

    public function run(){
        parent::run();
        $view = $this->getView();
        $view->registerJsFile('/js/js.cookie-2.2.0.min.js', ['depends'=> 'yii\web\JqueryAsset']);
        $tableEdit = <<<EDIT
        $(".table-edit").hide();
        $('.action-column').click(function(){
            $(".table-edit").toggle();
            $(".table-view").toggle();
            if($(this).html() == "编辑"){
                $(this).html("查看");
            }else{
                $(this).html("编辑");
            }
        });
EDIT;
        $view->registerJs($tableEdit);
        if(!$this->showColumns || count($this->columns) <= $this->minColumns){
            return ;
        }
        $this->_cookieFields = array_unique($this->_cookieFields);
        setcookie($this->_cookieName, implode('&', $this->_cookieFields), time() + 86400 * 30, '/');//一个月
        $js = <<<JS
        var cookieName = '{$this->_cookieName}';
        jQuery('#{$this->select_columns} input[type="checkbox"]').bind('click',function(){
            var cookieValue = '';
            jQuery('#{$this->select_columns} :checkbox').each(function(){
                if($(this).is(":checked")){
                    if(cookieValue){
                        cookieValue = cookieValue +"&"+ $(this).attr('name');
                    }else{
                        cookieValue = $(this).attr('name');
                    }
                }
            });
            Cookies.set(cookieName, cookieValue, {expires:30, path:"/"});

            var index=$(this).attr('column_index');
            jQuery('#{$this->id} tr').each(function(){
                $($(this).find('th').get(index)).toggle();
                $($(this).find('td').get(index)).toggle();
            });});
            var checkboxList = jQuery('#{$this->select_columns} input[type="checkbox"]');
            for(var index = 0; index < checkboxList.length; index ++){
                var column_index = $(checkboxList[index]).attr("column_index");
                var checked = $(checkboxList[index]).is(":checked");
                 if(checked){
                    jQuery('#{$this->id} tr').find('th:eq('+column_index+')').show();
                    jQuery('#{$this->id} tr').find('td:eq('+column_index+')').show();
                }else{
                    jQuery('#{$this->id} tr').find('th:eq('+column_index+')').hide();
                    jQuery('#{$this->id} tr').find('td:eq('+column_index+')').hide();
                }
            }
JS;
        $view->registerJs("jQuery('#{$this->id}').before('<div id=\'{$this->select_columns}\'></div>');jQuery('#{$this->select_columns}').html('$this->_html');$js",\yii\web\View::POS_READY);
    }
}

?>
